<template>
    <div class="mainbox">
        <PageHeaderNav :need-underline="false" :need-back="true" content="个人信息"></PageHeaderNav>
        <van-form @submit="submit">
            <van-field name="uploader" label="头像">
                <template #input>
                    <van-uploader v-model="userInfo.headSculptureUrl" :after-read="afterRead"></van-uploader>
                </template>
            </van-field>
            <van-field
                v-model="userInfo.username"
                name="用户名"
                label="用户名"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
            ></van-field>
            <van-field name="radio" label="单选框">
                <template #input>
                    <van-radio-group v-model="userInfo.gender" direction="horizontal">
                        <van-radio name="男">男</van-radio>
                        <van-radio name="女">女</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                v-model="userInfo.email"
                name="邮箱"
                label="邮箱"
                placeholder="请输入邮箱"
                :rules="[{ required: true, message: '请填写邮箱' }]"
            ></van-field>
            <van-field
                clickable
                readonly
                :value="showBirthdayString"
                name="datetimePicker"
                label="生日"
                placeholder="请选择生日"
                @click="showPicker = true"
            ></van-field>
            <van-popup v-model="showPicker" position="bottom">
                <van-datetime-picker
                    v-model="userInfo.birthday"
                    :min-date="minDate"
                    :max-date="maxDate"
                    type="date"
                    @confirm="onConfirm"
                    @cancel="showPicker = false"

                />
            </van-popup>
            <van-button round block type="info" native-type="submit" class="btnFocus" id="submit">提 交</van-button>
        </van-form>
    </div>
</template>

<script>
import PageHeaderNav from "@/components/Publlic/PageHeaderNav.vue";

export default {
    components: {
        PageHeaderNav
    },

    data() {
        return {
            // 用户信息
            userInfo: {
                username: this.$store.state.UserModule.userInfo.username,
                email: this.$store.state.UserModule.userInfo.email,
                gender: this.$store.state.UserModule.userInfo.gender,
                birthday: this.$public.timeStampToDate(this.$store.state.UserModule.userInfo.birthday),
                headSculptureUrl: [{url: this.$store.state.UserModule.userInfo.headSculptureUrl}],
            },

            // 生日选择器
            showPicker: false,
            minDate: new Date(new Date(1900, 1, 1).setHours(0, 0, 0, 0)),
            maxDate: new Date(new Date(new Date().getFullYear(), 12, 12).setHours(0, 0, 0, 0)),
        }
    },

    methods: {
        // 选择头像的事件
        afterRead(file) {
            // 清理头像显示个数，只能显示最后选择的那一个
            if (this.userInfo.headSculptureUrl.length > 1) this.userInfo.headSculptureUrl.shift()
        },

        // 选好时间的事件
        onConfirm(date) {
            // 时间框同步显示时间
            const timeStamp = this.$public.dateToTimeStampString(date)
            this.userInfo.birthday = this.$public.formatTimeStampToYYMMDD(timeStamp)
            // 关闭时间选择器
            this.showPicker = false
        },

        // 提交事件
        async submit() {
            // 验证填写邮箱是否规范
            const email = this.userInfo.email
            let reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
            if (!reg.test(email)) return this.$message({
                message: '请输入正确的电子邮箱',
                type: 'warning'
            })

            // 按钮防抖
            const buttonEle = document.getElementById("submit")
            this.$public.bottomDisableOrAllow(buttonEle,"正在保存...", true)

            // 图片文件
            let formData = new FormData()
            let headSculptureFile = this.userInfo.headSculptureUrl[0].file || null

            // 图片压缩
            if (headSculptureFile) {
                this.$message({
                    message: '正在压缩头像...',
                    type: 'success'
                })
                headSculptureFile = await this.$public.cutImage(headSculptureFile, 1024 * 1024 / 2)
            }

            formData.append("headSculptureFile", headSculptureFile)
            formData.append("username", this.userInfo.username)
            formData.append("email", this.userInfo.email)
            formData.append("gender", this.userInfo.gender)
            formData.append("birthday", this.$public.dateToTimeStampString(this.userInfo.birthday))

            this.request.post("/user/saveUserInfo/", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                },
            }).then((response) => {
                const status = response["code"] === 200

                if (status) {
                    setTimeout(() => {
                        this.$router.push("/userView/")
                    }, 500)
                }

                this.$public.bottomDisableOrAllow(buttonEle,"提 交", false)
            }).catch((error) => {
                this.$public.bottomDisableOrAllow(buttonEle,"提 交", false)
            })
        }
    },

    computed: {
        showBirthdayString() {
            return this.$public.formatTimeStampToYYMMDD(this.$public.dateToTimeStampString(this.userInfo.birthday))
        }
    }
}
</script>

<style lang="less" scoped>
.mainbox {
    background: #F4F4F4;
    height: 100%;
    width: 100%;
}

.van-cell {
    line-height: 48px;
    font-size: 18px;
}

.van-button {
    height: 50px;
    margin-top: 15px;
    background-color: var(--color);
    border-radius: 0;
    outline: none;
    font-size: 22px;
    border: none;
}

::v-deep .van-cell__value {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

::v-deep .van-field__control {
    background-color: white;
}
</style>